#include "string.h"
#include <cstring>

using std::cout;
using std::endl;

int String::num_strings = 0;

// constructor
String::String(const char * s)
{
    len = std::strlen(s);
    str = new char[len + 1];
    std::strcpy(str, s);

    ++num_strings;
}
// default constructor
String::String()
{
    len = 0;
    str = new char[1];
    str[0] = '\0';

    ++num_strings;
}
// copy constructor
String::String(const String & st)
{
    len = st.len;
    str = new char[len + 1];
    std::strcpy(str, st.str);

    ++num_strings;
}
String::~String()
{
    delete [] str;

    --num_strings;
}


//= operator
String & String::operator=(const String & st)
{
    if (this == &st)
        return *this;

    delete [] str;

    len = st.len;
    str = new char[len + 1];
    std::strcpy(str, st.str);

    return *this; // 用于连续赋值
}
String & String::operator=(const char * st)
{
    delete [] str;

    len = std::strlen(st);
    str = new char[len + 1];
    std::strcpy(str, st);
    
    return *this; // 用于连续赋值
}

char & String::operator[](int i)
{
    return str[i];
}
const char & String::operator[](int i) const
{
    return str[i];
}

//friend function
bool operator<(const String &st, const String &st2)
{
    return (std::strcmp(st.str, st2.str) < 0);
}
bool operator>(const String &st, const String &st2)
{
    return st2 < st;
    // return (std::strcmp(st.str, st2.str) > 0);
}
bool operator==(const String &st, const String &st2)
{
    return (std::strcmp(st.str, st2.str) == 0);
}

std::ostream & operator<<(std::ostream & os, const String & st)
{
    os << st.str;
    return os;
}
std::istream & operator>>(std::istream & is, String & st)
{
    char temp[String::CINLIM];
    is.get(temp, String::CINLIM);
    if (is)
        st = temp;  // 因为重载了赋值运算符 String & String::operator=(const char * st)

    while (is && is.get() != '\n')  // 清空输入队列
       continue;

    return is;
}